package com.task.quartz;


import com.task.quartz.job.TestQuartz1;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.task.quartz.job.TestQuartz2;

/**
 * 配置类
 *
 * @author sunhui
 * @date 2018/4/26
 */
@Configuration
public class QuartzConfig {

    @Bean
    public JobDetail testQuartz1JobDetail() {
        return JobBuilder.newJob(TestQuartz1.class).withIdentity("testQuartz1").storeDurably().build();
    }

    /**
     * 任务1
     * 使用QuartzJobBean + SimpleScheduleBuilder方式
     *
     * @return
     */
    @Bean
    public Trigger testQuartz1() {
        SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule()
                //设置时间周期单位秒
                .withIntervalInSeconds(10)
                //设置时间周期单位分钟
                //.withIntervalInMinutes(10)
                .repeatForever();
        return TriggerBuilder.newTrigger().forJob(testQuartz1JobDetail())
                .withIdentity("testQuartz1")
                .withSchedule(scheduleBuilder)
                .build();
    }

    /**
     * 任务2
     * 使用Job+StdSchedulerFactory方式
     *
     * @return
     */
    @Bean
    public boolean testQuartz2() {
        try {
            //创建一个定时器对象
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

            //创建一个jobDetail对象
            JobDetail jobDetail = JobBuilder.newJob(TestQuartz2.class).withIdentity("job_2", "group_2").build();

            //创建一trigger
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger_2", "group_2")
                    .startNow().withSchedule(CronScheduleBuilder.cronSchedule("0/2 * * * * ?")).build();
            scheduler.scheduleJob(jobDetail, trigger);
            scheduler.start();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return true;
    }
}